import { SoundIcon } from './SoundIcon'
// 声音图标组件
import usePronunciationSound from '@/hooks/usePronunciation'
// 播放发音的自定义钩子
import type { Word } from '@/typings'
// 单词类型
import { useCallback, useEffect, useImperativeHandle } from 'react'
// React 相关钩子
import React from 'react'

//   React

export const WordPronunciationIcon = React.forwardRef<
  WordPronunciationIconRef,
  { word: Word; lang: string; className?: string; iconClassName?: string }
>(({ word, lang, className, iconClassName }, ref) => {
  const currentWord = () => {
    if (lang === 'hapin') {
      if (/[\u0400-\u04FF]/.test(word.notation || '')) {
        // 哈萨克语西里尔文字
        return word.notation || ''
      } else {
        // 哈萨克语老文字
        return word.trans[2]
      }
    } else {
      return word.name
    }
  } // 获取当前单词发音文本
  const { play, stop, isPlaying } = usePronunciationSound(currentWord()) // 播放发音的钩子

  const playSound = useCallback(() => {
    stop() // 停止播放声音
    play() // 播放声音
  }, [play, stop]) // 播放声音的回调函数

  useEffect(() => {
    return stop // 停止播放声音
  }, [word, stop])

  useImperativeHandle(
    ref,
    () => ({
      play: playSound,
    }),
    [playSound],
  ) // 给传过来的ref绑定play方法

  return (
    <SoundIcon
      animated={isPlaying}
      onClick={playSound}
      className={`cursor-pointer text-gray-600 ${className}`}
      iconClassName={iconClassName}
    />
  )
}) // 单词发音图标组件

WordPronunciationIcon.displayName = 'WordPronunciationIcon'

export type WordPronunciationIconRef = {
  play: () => void // 播放单词发音
} // 播放单词发音
